import React, { useState } from 'react';
import { Button, Space, Card, Typography, Alert } from 'antd';
import { BugOutlined, ExperimentOutlined } from '@ant-design/icons';

const { Title, Paragraph } = Typography;

// 一个会故意抛出错误的组件
const BuggyComponent: React.FC<{ shouldThrow: boolean }> = ({ shouldThrow }) => {
  if (shouldThrow) {
    throw new Error('这是一个测试错误 - 错误边界测试成功！');
  }
  
  return <div>我是一个正常的组件</div>;
};

// 另一个会在异步操作中抛出错误的组件
const AsyncBuggyComponent: React.FC<{ shouldThrow: boolean }> = ({ shouldThrow }) => {
  React.useEffect(() => {
    if (shouldThrow) {
      // 异步错误不会被错误边界捕获，需要其他方式处理
      setTimeout(() => {
        throw new Error('这是一个异步错误 - 不会被错误边界捕获');
      }, 100);
    }
  }, [shouldThrow]);
  
  return <div>我是一个异步组件</div>;
};

/**
 * 错误边界测试组件
 * 用于测试和演示错误边界的功能
 */
const ErrorBoundaryTest: React.FC = () => {
  const [throwSyncError, setThrowSyncError] = useState(false);
  const [throwAsyncError, setThrowAsyncError] = useState(false);
  const [componentKey, setComponentKey] = useState(0);

  const handleReset = () => {
    setThrowSyncError(false);
    setThrowAsyncError(false);
    setComponentKey(prev => prev + 1);
  };

  const handleThrowSyncError = () => {
    setThrowSyncError(true);
  };

  const handleThrowAsyncError = () => {
    setThrowAsyncError(true);
  };

  const handleManualError = () => {
    // 手动报告错误到后台
    try {
      chrome.runtime.sendMessage({
        type: 'ERROR_REPORT',
        payload: {
          id: `MANUAL_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
          message: '手动报告的测试错误',
          stack: 'at handleManualError\\nat onClick',
          componentStack: 'in ErrorBoundaryTest',
          timestamp: Date.now(),
          url: window.location.href
        }
      });
      console.log('手动错误已报告到后台');
    } catch (e) {
      console.error('无法发送错误报告:', e);
    }
  };

  return (
    <div style={{ padding: '20px', maxWidth: '800px', margin: '0 auto' }}>
      <Card>
        <Title level={2}>
          <BugOutlined style={{ marginRight: '8px' }} />
          错误边界测试页面
        </Title>
        
        <Alert
          message="测试说明"
          description={
            <div>
              <Paragraph>
                这个页面用于测试错误边界的功能。点击下面的按钮来触发不同类型的错误：
              </Paragraph>
              <ul>
                <li><strong>同步错误</strong>：会被错误边界捕获并显示友好的错误页面</li>
                <li><strong>异步错误</strong>：不会被错误边界捕获，会显示在控制台中</li>
                <li><strong>手动报告</strong>：模拟向后台发送错误报告</li>
              </ul>
            </div>
          }
          type="info"
          showIcon
          style={{ marginBottom: '20px' }}
        />

        <Space direction="vertical" size="large" style={{ width: '100%' }}>
          <Card size="small" title="控制面板">
            <Space wrap>
              <Button 
                type="primary" 
                danger 
                icon={<BugOutlined />}
                onClick={handleThrowSyncError}
                disabled={throwSyncError}
              >
                触发同步错误
              </Button>
              
              <Button 
                type="default" 
                danger 
                icon={<ExperimentOutlined />}
                onClick={handleThrowAsyncError}
                disabled={throwAsyncError}
              >
                触发异步错误
              </Button>
              
              <Button 
                type="default"
                onClick={handleManualError}
              >
                手动报告错误
              </Button>
              
              <Button 
                type="dashed"
                onClick={handleReset}
              >
                重置状态
              </Button>
            </Space>
          </Card>

          <Card size="small" title="测试组件区域" key={componentKey}>
            <Space direction="vertical" style={{ width: '100%' }}>
              <Card type="inner" title="同步错误测试">
                <BuggyComponent shouldThrow={throwSyncError} />
              </Card>
              
              <Card type="inner" title="异步错误测试">
                <AsyncBuggyComponent shouldThrow={throwAsyncError} />
              </Card>
            </Space>
          </Card>

          <Card size="small" title="错误日志">
            <Button 
              type="link" 
              onClick={() => {
                const logs = localStorage.getItem('extension-error-logs');
                if (logs) {
                  console.log('本地错误日志:', JSON.parse(logs));
                  alert('错误日志已输出到控制台');
                } else {
                  alert('暂无错误日志');
                }
              }}
            >
              查看本地错误日志
            </Button>
            
            <Button 
              type="link" 
              onClick={() => {
                localStorage.removeItem('extension-error-logs');
                alert('本地错误日志已清空');
              }}
            >
              清空本地日志
            </Button>
          </Card>
        </Space>
      </Card>
    </div>
  );
};

export default ErrorBoundaryTest;